package controller

import (
	"control/common"
	"control/dto"
	"control/model"
	"control/respones"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"log"
	"net/http"
)

// 功能：查询手机号在系统中是否存在
func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone = ?", telephone).First(&user)
	if user.ID != 0 {
		return true
	} else {
		return false
	}
}

// 功能：查询用户名在系统中是否存在
func isUserExist(db *gorm.DB, username string) bool {
	var user model.User
	db.Where("username = ?", username).First(&user)
	if user.ID != 0 {
		return true
	} else {
		return false
	}
}

// 功能：用户注册
func Register(c *gin.Context) {
	DB := common.GetDB()
	username := c.PostForm("username")
	telephone := c.PostForm("telephone")
	password := c.PostForm("password")

	// 数据验证
	if len(telephone) != 11 {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"code": http.StatusUnprocessableEntity, "msg": "手机号必须为11位"})
		return
	}
	// 查询手机号是否存在
	if isTelephoneExist(DB, telephone) {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"code": http.StatusUnprocessableEntity, "msg": "用户已经存在"})
		return
	}
	if len(username) < 4 {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"code": http.StatusUnprocessableEntity, "msg": "用户名不能少于4位"})
		return
	}
	if isUserExist(DB, username) {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"code": http.StatusUnprocessableEntity, "msg": "用户已经存在"})
		return
	}
	if len(password) < 6 {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"code": http.StatusUnprocessableEntity, "msg": "密码不能少于6位"})
		return
	}
	// hash加密
	hashdPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		// 返回内部错误500
		c.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "msg": "密码不能少于6位"})
	}

	//创建用户
	newUser := model.User{
		Username:  username,
		Telephone: telephone,
		Password:  string(hashdPassword),
	}
	DB.Create(&newUser)
	// 返回注册成功
	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "msg": "注册成功"})
	log.Println(username, password, telephone)

}

func Login(c *gin.Context) {
	var user model.User
	DB := common.GetDB()

	username := c.PostForm("username")
	password := c.PostForm("password")

	// 查询用户是否存在
	//if !isUserExist(DB, username) {
	//	c.JSON(http.StatusUnprocessableEntity, gin.H{"code": http.StatusUnprocessableEntity, "msg": "未查询到用户"})
	//	return
	//}
	DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		respones.Response(c, http.StatusUnprocessableEntity, http.StatusUnprocessableEntity, nil, "用户名或密码错误")
		return
	}

	// 数据验证
	if len(username) < 4 {
		respones.Response(c, http.StatusUnprocessableEntity, http.StatusUnprocessableEntity, nil, "用户名不能少于4位")
		return
	}

	// 判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		log.Println(user.Password)
		log.Println(password)
		respones.Response(c, http.StatusBadRequest, http.StatusBadRequest, nil, "StatusBadRequest")
		return
	}

	// 发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		respones.Response(c, http.StatusInternalServerError, http.StatusInternalServerError, nil, "系统异常")
		log.Println("Token generate error", err)
		return
	}

	respones.Response(c, http.StatusOK, http.StatusOK, gin.H{"token": token}, "登录成功")
	// 返回结果

	log.Println(username, password)

}

// 返回用户基本信息
func Info(c *gin.Context) {
	// 用户应从上下文中获取
	user, _ := c.Get("user")
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": gin.H{
			// 使用结构体转换，将转换后的数据返回给前端
			"user": dto.ToUserDto(user.(model.User)),
		},
	})
}
